import React, { Component } from 'react';
import { Table, Tabs, Input, Button, Form, Modal } from 'antd';
import { apiServiceProviderPage, apiServiceProviderReview } from '@/request/callServicer/servicer'
import TheQueryForm from '@/components/TheQueryForm';
import TheButton from '@/components/TheButton';

import store from "@/store/store"
const { confirm } = Modal;

const { TabPane } = Tabs;
const { TextArea } = Input;
export default class ServerAuth extends Component {
  constructor() {
    super()
    this.queryFormRef = React.createRef()
    this.formRef = React.createRef()
    this.state = {
      isModalVisible: false,
      searchOption: [
        { field: 'name', label: '服务者姓名/id', placeholder: '支持模糊查询', required: false, rules: [], type: 'Input', defaultValue: '' },
        { field: 'mobile', label: '服务者手机号', placeholder: '请输入服务者手机号', required: false, rules: [], type: 'Input', defaultValue: '' },
        {
          field: 'approvalStatus', label: '审核状态', placeholder: '请选择审核状态', required: false, rules: [], type: 'Select', defaultValue: '',
          options: [{ label: '待审批', value: '0', }, { label: '已通过', value: '1' }, { label: '已驳回', value: '2', }, { label: '已撤回', value: '3' }]
        }
      ],

      columns: [
        {
          title: 'ID',
          dataIndex: 'serviceProviderId',
          key: 'serviceProviderId',
          width: 150

        },
        {
          title: '服务者姓名',
          dataIndex: 'name',
          width: 120,
          key: 'name',
          render: (text, content) => <div style={{ width: '150px', wordBreak: 'break-all', whiteSpace: 'break-spaces' }}>{text}</div>

        },
        {
          title: '手机号',
          dataIndex: 'mobile',
          key: 'mobile',
          width: 120,

          render: (text, content) => <div style={{ width: '250px', wordBreak: 'break-all', whiteSpace: 'break-spaces' }}>{text}</div>

        },
        {
          title: '申请时间',
          dataIndex: 'createTime',
          key: 'createTime',
          width: 150
        },
        {
          title: '状态',
          dataIndex: 'approvalStatus',
          key: 'approvalStatus',
          width: 80,
          render: (text, content) => {
            let txt = ''
            if (text == 0) {
              txt = '待审批'
            } else if (text == 1) {
              txt = '已通过'
            } else if (text == 2) {
              txt = '已驳回'
            } else if (text == 3) {
              txt = '已撤回'
            }
            return <div style={{ width: '120px', wordBreak: 'break-all', whiteSpace: 'break-spaces' }}>
              {txt}
            </div>
          }

        },

        {
          title: '操作',
          dataIndex: 'operate',
          key: 'operate',
          width: 120,
          render: (text, content) => {
            return (
              <div>
                {
                  content.approvalStatus == 0 ? (<span>
                    <TheButton haspermi={['call:servicerApplyList:pass']} type='link'   onClick={() => this.handleReviewPass(content, 1)}>通过</TheButton>
                    <TheButton haspermi={['call:servicerApplyList:reject']} type='link' onClick={() => this.handleReviewReject(content, 2)}>驳回</TheButton>
                  </span>) : null

                }

                <TheButton haspermi={['call:servicerApplyList:view']} type='link' onClick={() => this.handleLook(content)}>查看</TheButton>
              </div>
            )
          }
        },
      ],
      dataSource: [],
      queryForm: {},
      pageData: {
        pageNo: 1,
        pageSize: 10,

      },
      total: 0,

      searchParams: {
        name: '',
        mobile: ''
      },


    }
  }
  componentDidMount() {
    let searchParams = store.getState().searchValue
    let { pageNo, pageSize, queryForm, pathName } = searchParams
    if (searchParams && pageNo && pathName == 'servicerApplyList') {
      this.setState({
        queryForm,
        pageData: {
          pageNo: pageNo, pageSize: pageSize
        }
      }, () => {
        this.queryFormRef.onSetDefault({
          ...queryForm
        })
        this.getData()
      })
    } else {
      this.getData()
    }
  }
  getData = (values) => {
    let { pageNo, pageSize } = this.state.pageData

    this.setState({
      queryForm: values === undefined ? this.state.queryForm : { ...values }
    }, async () => {
      const params = {
        pageNo, pageSize, queryForm: this.state.queryForm
      }
      store.dispatch({
        type: 'SaveSearchValues',
        data: {
          pathName: 'servicerApplyList',
          ...params
        }
      })
      apiServiceProviderPage({ pageNo, pageSize, ...this.state.queryForm }).then(res => {
        if (res.code == 0) {
          this.setState({
            dataSource: res.data,
            pageData: {
              ...this.state.pageData,
            },
            total: res.totalCount,
            onChange: this.pageChange
          })
        }
      })
    })
  }
  handleReviewPass = (item, approvalStatus) => {
    confirm({
      title: '提醒',
      content: '审核通过后，仍需要对该服务者进行服务培训，培训完成后修改该服务者的服务技能之后，该服务者打开对应服务的接单状态后，方可开始正式接单！是否继续通过审核？',
      okText: '通过',
      cancelText: '取消',
      onOk: () => {
        apiServiceProviderReview({
          serviceProviderId: item.serviceProviderId,
          approvalStatus: 1,
          approvalMsg: item.approvalMsg
        }).then(res => {
          if (res.code == 0) {
            React.$message({ type: 'success', content: `操作成功` })
            this.getData()
          }
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }
  handleReviewReject = (item, approvalStatus) => {
    this.setState({
      isModalVisible: true
    }, () => {
      this.formRef.current.setFieldsValue({
        serviceProviderId: item.serviceProviderId,
        approvalStatus
      })
    })
  }
  handlePass = () => {
    this.formRef.current.validateFields().then(async values => {
      apiServiceProviderReview({
        serviceProviderId: values.serviceProviderId,
        approvalStatus: values.approvalStatus,
        approvalMsg: values.approvalMsg
      }).then(res => {
        if (res.code == 0) {
          React.$message({ type: 'success', content: `操作成功` })
          this.getData()
        }
        this.setState({ isModalVisible: false })
      })
    })

  }
  onCancel = () => {
    this.formRef.current.resetFields()
    this.setState({
      isModalVisible: false
    })
  }
  handleLook = (row) => {
    this.props.history.push({
      pathname: `/call/servicer/servicerApplyList/detail/${row.serviceProviderId}/${row.approvalStatus !== 0 ? 'review' : 'view'}`,

    })
  }
  pageChange = (pageNo, pageSize) => {
    console.log(pageNo, pageSize)
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      this.getData()
    })
  };
  onReset() {
    this.setState({
      queryForm: {}
    }, () => {
      this.pageChange(1, 10)
    })
  }
  onFormSearch(values) {
    this.setState({
      pageData: { pageNo: 1, pageSize: 10 }
    }, () => {
      this.getData(values)
    })
  }



  render() {
    const { columns, dataSource, isModalVisible, pageData, searchOption, total } = this.state

    return (
      <div className='p-layout-box'>
        <TheQueryForm ref={(ref) => this.queryFormRef = ref} labelCol={10} show={true} option={searchOption}
          onReset={() => this.onReset()}
          onGetValues={(values) => this.onFormSearch(values)} >
        </TheQueryForm>
        <Table columns={columns} dataSource={dataSource} pagination={{
          total: total,
          position: ['bottomCenter'],
          onChange: this.pageChange
        }}
          scroll={{
            y: '60vh',
          }}
          bordered
          onChange={this.onChange} />
        <Modal title="驳回申请" visible={isModalVisible} okText="驳回申请" onOk={() => this.handlePass(2)} onCancel={() => this.onCancel()}  >
          <Form
            ref={this.formRef}
            name="basic"
            layout={'vertical'}
            autoComplete="off"
          >
            <Form.Item
              hidden
              name="approvalStatus"
            ><Input></Input>
            </Form.Item>
            <Form.Item
              hidden
              name="serviceProviderId"
            ><Input></Input>
            </Form.Item>
            <Form.Item
              label="说明:"
              required
              name="approvalMsg"
              rules={[
                {
                  required: true,
                  message: '请输入驳回原因及建议的整改措施',
                }
              ]}
            >
              <TextArea maxLength={200} placeholder='请输入驳回原因及建议的整改措施' />
            </Form.Item>
          </Form>
        </Modal>
      </div >
    );
  }
}
